package org.example.system.config;

import cn.hutool.captcha.generator.CodeGenerator;
import org.example.system.security.constant.SecurityConstants;
import org.example.system.security.exception.MyAccessDeniedHandler;
import org.example.system.security.exception.MyAuthenticationEntryPoint;
import org.example.system.filter.JwtValidationFilter;
import org.example.system.filter.CaptchaValidationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Spring Security 权限配置
 * 配置安全过滤器链、密码编码器和认证管理器
 *
 * @author LY
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final MyAuthenticationEntryPoint authenticationEntryPoint;
    private final MyAccessDeniedHandler accessDeniedHandler;
    private final RedisTemplate<String, Object> redisTemplate;
    private final CodeGenerator codeGenerator;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 配置请求授权
        configureAuthorization(http);

        // 配置会话管理为无状态
        http.sessionManagement(configurer -> configurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

        // 配置异常处理
        configureExceptionHandling(http);

        // 禁用 CSRF
        http.csrf(AbstractHttpConfigurer::disable);

        // 添加自定义过滤器
        addCustomFilters(http);

        return http.build();
    }

    /**
     * 配置HttpSecurity以设置授权规则
     * 此方法定义了哪些请求可以被所有用户访问（无需认证），哪些请求需要用户认证后才能访问
     *
     * @param http HttpSecurity实例，用于配置Web安全
     * @throws Exception 配置过程中可能抛出的异常
     */
    private void configureAuthorization(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(requestMatcherRegistry ->
                requestMatcherRegistry
                        .requestMatchers(SecurityConstants.CAPTCHA_PATH).permitAll()
                        .requestMatchers(SecurityConstants.LOGIN_PATH).permitAll()
                        .requestMatchers(SecurityConstants.REGISTER_PATH).permitAll()
                        .requestMatchers(
                                "/webjars/**",
                                "/doc.html",
                                "/swagger-resources/**",
                                "/v3/api-docs/**",
                                "/swagger-ui/**",
                                "/swagger-ui.html",
                                "/ws/**",
                                "/ws-app/**")
                        .permitAll()
                        .anyRequest().authenticated()
        );
    }

    /**
     * 配置异常处理
     * <p>
     * 在Spring Security中，定制异常处理机制，用于处理未认证和无访问权限的情况
     *
     * @param http HttpSecurity实例，用于配置Spring Security
     * @throws Exception 配置过程中可能抛出的异常
     */
    private void configureExceptionHandling(HttpSecurity http) throws Exception {
        http.exceptionHandling(httpSecurityExceptionHandlingConfigurer ->
                httpSecurityExceptionHandlingConfigurer
                        .authenticationEntryPoint(authenticationEntryPoint)
                        .accessDeniedHandler(accessDeniedHandler)
        );
    }

    /**
     * 添加自定义过滤器到HttpSecurity中
     *
     * @param http HttpSecurity实例，用于配置Web安全
     */
    private void addCustomFilters(HttpSecurity http) {
        // 在UsernamePasswordAuthenticationFilter之前添加验证码验证过滤器
        http.addFilterBefore(new CaptchaValidationFilter(redisTemplate, codeGenerator), UsernamePasswordAuthenticationFilter.class);
        // 在UsernamePasswordAuthenticationFilter之前添加JWT验证过滤器
        http.addFilterBefore(new JwtValidationFilter(redisTemplate), UsernamePasswordAuthenticationFilter.class);
    }

    /**
     * 密码编码器
     *
     * @return {@link PasswordEncoder}
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * AuthenticationManager 手动注入
     *
     * @param authenticationConfiguration 认证配置
     * @return {@link AuthenticationManager}
     * @throws Exception 异常
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
}